public class MyStackList implements IStack{
    //用单链表实现栈

    static class ListNode {

        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;


    @Override
    public void push(int val) {
        ListNode node = new ListNode(val);
        if(head == null) {
            head = node;
            return;
        }
        node.next = head;
        head = node;
    }

    @Override
    public int pop() {
        if(head == null) {
            System.out.println("栈为空！");
            return -1;
        }
        int tmp = head.val;
        head = head.next;
        return tmp;
    }

    @Override
    public int peek() {
        //查看栈顶元素
        if(head == null) {
            System.out.println("栈为空");
            return -1;
        }
        return head.val;
    }

    @Override
    public int size() {
        if(head == null) {
            return 0;
        }
        ListNode cur = head;
        int count = 0;
        while(cur != null) {
            count++;
            cur =cur.next;
        }
        return count;
    }

    @Override
    public boolean empty() {
        return head==null;
    }
}
